import * as vscode from 'vscode';
import { ApiClient, AnalysisRequest } from '../utils/apiClient';

export class CodeAnalysisService {
    private apiClient: ApiClient;

    constructor(apiClient: ApiClient) {
        this.apiClient = apiClient;
    }

    async analyzeCode(
        editor: vscode.TextEditor,
        token: vscode.CancellationToken
    ): Promise<any> {
        const codeContext = this.buildCodeContext(editor);
        
        const request: AnalysisRequest = {
            context: codeContext,
            analysisTypes: ['syntax', 'style', 'security', 'performance'],
            useCodeQL: true,
            severityLevel: 'warning',
            includeFix: true
        };

        return await this.apiClient.analyzeCode(request);
    }

    private buildCodeContext(editor: vscode.TextEditor): any {
        const document = editor.document;
        const position = editor.selection.active;
        
        return {
            filePath: document.fileName,
            code: document.getText(),
            cursorLine: position.line,
            cursorColumn: position.character,
            language: this.detectLanguage(document.fileName),
            projectRoot: this.getProjectRoot(document.uri),
            includes: this.extractIncludes(document.getText()),
            namespace: this.extractNamespace(document.getText(), position.line),
            className: this.extractClassName(document.getText(), position.line),
            functionName: this.extractFunctionName(document.getText(), position.line)
        };
    }

    private detectLanguage(fileName: string): string {
        if (fileName.endsWith('.c')) return 'c';
        if (fileName.endsWith('.cpp') || fileName.endsWith('.cc') || fileName.endsWith('.cxx')) return 'cpp';
        if (fileName.endsWith('.h')) return 'cpp';
        if (fileName.endsWith('.gn')) return 'gn';
        return 'cpp';
    }

    private getProjectRoot(uri: vscode.Uri): string {
        const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri);
        return workspaceFolder ? workspaceFolder.uri.fsPath : '';
    }

    private extractIncludes(code: string): string[] {
        const includeRegex = /#include\s*[<"]([^>"]+)[>"]/g;
        const includes: string[] = [];
        let match;
        
        while ((match = includeRegex.exec(code)) !== null) {
            includes.push(match[1]);
        }
        
        return includes;
    }

    private extractNamespace(code: string, cursorLine: number): string | undefined {
        const lines = code.split('\n');
        for (let i = 0; i < Math.min(cursorLine, lines.length); i++) {
            const line = lines[i].trim();
            const namespaceMatch = line.match(/namespace\s+(\w+)/);
            if (namespaceMatch) {
                return namespaceMatch[1];
            }
        }
        return undefined;
    }

    private extractClassName(code: string, cursorLine: number): string | undefined {
        const lines = code.split('\n');
        for (let i = 0; i < Math.min(cursorLine, lines.length); i++) {
            const line = lines[i].trim();
            const classMatch = line.match(/class\s+(\w+)/);
            if (classMatch) {
                return classMatch[1];
            }
        }
        return undefined;
    }

    private extractFunctionName(code: string, cursorLine: number): string | undefined {
        const lines = code.split('\n');
        for (let i = 0; i < Math.min(cursorLine, lines.length); i++) {
            const line = lines[i].trim();
            const functionMatch = line.match(/(\w+)\s*\([^)]*\)\s*{/);
            if (functionMatch) {
                return functionMatch[1];
            }
        }
        return undefined;
    }
}
